﻿using System;
using System.Data;
using System.Data.SqlClient;
using DataAccess.Interfaces;

namespace DataAccess.Implementations
{
    public class SqlHelper : ISqlHelper
    {
        private const string CONNECTION_STRING = @"Data Source=IND10023\MSSQL2008;Initial Catalog=nh;User ID=sa;Password=sa";
        private readonly SqlConnection _connection;
        private SqlCommand _command;

        public SqlHelper()
        {
            _connection = new SqlConnection(CONNECTION_STRING);
        }

        public  void OpenConnection()
        {
            _connection.Open();
        }

        public  void CloseConnection()
        {
            _connection.Close();
            _connection.Dispose();
        }

        //private  SqlConnection Connection { get { return _connection; } }
        //private  SqlCommand Command { get { return _command; } }

        public  void AddParameter(string name, SqlDbType type, ParameterDirection direction, object value)
        {
            SqlParameter specialityParam = _command.Parameters.Add(name, type);
            specialityParam.Direction = direction;
            specialityParam.Value = value;
        }

        public void CreateCommand(string cmdText, CommandType cmdType)
        {
            _command = new SqlCommand(cmdText, _connection) {CommandType = cmdType};
        }

        public SqlDataReader ExecuteReader(CommandBehavior cmdBehaviour)
        {
            return _command.ExecuteReader(cmdBehaviour);
        }

        ~SqlHelper()
        {
            CloseConnection();
        }
    }

    public static class SqlUtil
    {
        public static T SetValue<T>(object dataValue, T defaultValue)
        {
            return _IsTypeSqlParameter(dataValue) ? _Convert(((SqlParameter)dataValue).Value, defaultValue) : _Convert(dataValue, defaultValue);
        }

        private static T _Convert<T>(object val, T defaultTo)
        {
            T retValue = defaultTo;
            if(!(val == null || val == DBNull.Value))
            {
                retValue = (T)val;
                //switch (Type.GetTypeCode(defaultTo.GetType()))
                //{
                //    case TypeCode.Boolean :
                //        retValue = (T)val;
                //        break;
                //    default:
                //        break;
                //}
            }

            return retValue;
        }

        private static bool _IsTypeSqlParameter(object dataValue)
        {
            if (dataValue == null)
                return false;

            bool retVal = dataValue is SqlParameter;

            return retVal;
        }
    }
}
